package com.cloudbroker.bcs.common.util;



import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by lili19289 on 2016/10/10.
 */
public class IPUtil {

    private static Logger log = Logger.getLogger(IPUtil.class);

    /**
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
     *
     * @param request
     * @return
     * @throws IOException
     */
    public  static String getIpAddress(HttpServletRequest request)  {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
        String ip = request.getHeader("x-forwarded-for");
        log.debug("request.getHeader(\"x-forwarded-for\")=" + ip);

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
            log.debug("request.getHeader(\"X-Forwarded-For\")=" + ip);
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            log.debug("request.getHeader(\"Proxy-Client-IP\")=" + ip);
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            log.debug("request.getHeader(\"WL-Proxy-Client-IP\")=" + ip);
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            log.debug("request.getHeader(\"HTTP_CLIENT_IP\")=" + ip);
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            log.debug("request.getHeader(\"HTTP_X_FORWARDED_FOR\")=" + ip);
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            log.debug("request.getRemoteAddr()=" + ip);
        }

        if(null != ip && ip.indexOf(',') != -1){
            //如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串 IP 值
            //取X-Forwarded-For中第一个非unknown的有效IP字符串
            //如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
            //用户真实IP为： 192.168.1.110
            //注意:当访问地址为 localhost 时 地址格式为 0:0:0:0:0:0:1
            log.debug("ip=" + ip);
            String[] ips = ip.split(",");
            for (int i = 0; i < ips.length; i++) {
                if(null != ips[i] && !"unknown".equalsIgnoreCase(ips[i])){
                    ip = ips[i];
                    break;
                }
            }

        }
        if("0:0:0:0:0:0:1".equals(ip)){
            log.warn("由于客户端访问地址使用 localhost，获取客户端真实IP地址错误，请使用IP方式访问");
        }
        request.setAttribute("remoteAddr",ip);
        return ip;
    }
}
